

package com.hazelcast.client.impl.statistics;

import com.hazelcast.client.impl.spi.ClientContext;
import com.hazelcast.client.impl.spi.ProxyManager;
import com.hazelcast.internal.metrics.DynamicMetricsProvider;
import com.hazelcast.internal.metrics.MetricDescriptor;
import com.hazelcast.internal.metrics.MetricsCollectionContext;
import com.hazelcast.nearcache.NearCacheStats;

import static com.hazelcast.internal.metrics.MetricDescriptorConstants.NEARCACHE_DISCRIMINATOR_NAME;
import static com.hazelcast.internal.metrics.MetricDescriptorConstants.NEARCACHE_PREFIX;

class NearCacheMetricsProvider implements DynamicMetricsProvider {

    private final ProxyManager proxyManager;

    NearCacheMetricsProvider(ProxyManager proxyManager) {
        this.proxyManager = proxyManager;
    }

    @Override
    public void provideDynamicMetrics(MetricDescriptor descriptor, MetricsCollectionContext context) {
        descriptor.withPrefix(NEARCACHE_PREFIX);

        ClientContext clientContext = proxyManager.getContext();
        if (clientContext == null) {
            return;
        }

        clientContext.getNearCacheManagers().values().stream().flatMap(nearCacheManager -> nearCacheManager.listAllNearCaches().stream()).forEach(nearCache -> {
            String nearCacheName = nearCache.getName();
            NearCacheStats nearCacheStats = nearCache.getNearCacheStats();
            context.collect(descriptor.copy().withDiscriminator(NEARCACHE_DISCRIMINATOR_NAME, nearCacheName), nearCacheStats);
        });
    }
}
